//
//  QSTabBarController.m
//  自定义tabbar
//
//  Created by apple on 2017/2/17.
//  Copyright © 2017年 Song. All rights reserved.
//

#import "QSTabBarController.h"
#import "QSClassificationViewController.h"
#import "QSNavigationController.h"
#import "QSCHomePageViewController.h"
#import "QSShoppingCartViewController.h"
#import "QSPersonalCenterViewController.h"
#import "QSLoginModuleTool.h"
#import "QSLoginViewController.h"
#import "SCLoginManager.h"
#import "QSCustomerServiceViewController.h"
#import "UITabBar+QSBadge.h"

@interface QSTabBarController ()<UITabBarControllerDelegate, HChatDelegate>
{
    NSInteger index;
    BOOL verifyFlag;    // 是否是由tabbar发起的登录验证
}
/** 播放的提示音 */
@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@property (nonatomic, strong) HVisitorInfo *vistorBaseData;
@end

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;

@implementation QSTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    // 监听登录成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginSuccess) name:kLoginSuccessNotification object:nil];
    // 退出客服界面通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDisAppearCustormerServiceVC) name:kDidDisappearCustomerScrviceVCNotification object:nil];
    
    // 首页
    QSCHomePageViewController *homePageVC = [[QSCHomePageViewController alloc] init];
    [self addChildVc:homePageVC title:@"首页" image:@"icon_home_unselected" selectedImage:@"icon_home_selected"];
    
    // 分类
    QSClassificationViewController *classificationVC = [[QSClassificationViewController alloc] initWithLeftViewWidth:kLeftDrawerWidth];
    [self addChildVc:classificationVC title:@"分类" image:@"icon_class_unselected" selectedImage:@"icon_class_selected"];
    
    // 客服
    UIViewController *customerServiceVC = [[UIViewController alloc] init];
    [self addChildVc:customerServiceVC title:@"客服" image:@"icon_service_unselected" selectedImage:@"icon_service_selected"];
    
    // 购物车
    QSShoppingCartViewController *shoppingCartVC = [[QSShoppingCartViewController alloc] initWithNibName:@"QSShoppingCartViewController" bundle:[NSBundle mainBundle]];
    [self addChildVc:shoppingCartVC title:@"购物车" image:@"icon_shoppingcar_unselected" selectedImage:@"icon_shoppingcar_selected"];
    
    // 个人
    QSPersonalCenterViewController *personalCenterVC = [[QSPersonalCenterViewController alloc] init];
    [self addChildVc:personalCenterVC title:@"个人" image:@"icon_my_unselected" selectedImage:@"icon_my_selected"];
    
    // 把self注册为SDK的delegate
    [self registerNotifications];
}

/**
 *  开启客服会话
 */
- (void)chatAction
{
    // 登录IM
    SCLoginManager *lgM = [SCLoginManager shareLoginManager];
    if (![lgM loginKefuSDK]/*[self loginKefuSDK:shouqian] 测试切换账号使用*/) {
        [QSSVProgressTool showFailStatus:@"您的网络异常，请检查网络后重试！"];
    }
}

#pragma mark - 注册环信
-(void)registerNotifications
{
    [self unregisterNotifications];
    
    [[HChatClient sharedClient].chat addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications
{
    [[HChatClient sharedClient].chat removeDelegate:self];
}

// 收到消息回调
- (void)messagesDidReceive:(NSArray *)aMessages {
    BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
    
    if (!isAppActivity) {
        [self.tabBar showBadgeOnItemIndex:2];
        [self _showNotificationWithMessage:aMessages];
    }else {
        if (index == 2) {
            [self.tabBar hideBadgeOnItemIndex:2];
        } else {
            [self.tabBar showBadgeOnItemIndex:2];
        }
        [self _playSoundAndVibration];
    }
}

- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages {
    for (HMessage *message in aCmdMessages) {
        NSString *msg = [NSString stringWithFormat:@"%@", message.ext];
        NSLog(@"receive cmd message: %@", msg);
    }
}

/**
 *  显示推送消息
 */
- (void)_showNotificationWithMessage:(NSArray *)messages
{
    HPushOptions *options = [[HChatClient sharedClient] getPushOptionsFromServerWithError:nil ];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == HPushDisplayStyleMessageSummary) {
        id<HDIMessageModel> messageModel  = messages.firstObject;
        NSString *messageStr = nil;
        switch (messageModel.bodyType) {
            case EMMessageBodyTypeText:
            {
                messageStr = ((EMTextMessageBody *)messageModel).text;
            }
                break;
            case EMMessageBodyTypeImage:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case EMMessageBodyTypeVideo:{
                messageStr = NSLocalizedString(@"message.vidio", @"Vidio");
            }
                break;
            default:
                break;
        }
        
        NSString *title = messageModel.message.from;
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    }
    
#pragma mark - 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = ++badge;
}

/**
 *  播放提示音
 */
- (void)_playSoundAndVibration
{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        QSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[HDCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[HDCDDeviceManager sharedInstance] playVibration];
}

/**
 *  添加子控制器
 */
- (void)addChildVc:(UIViewController *)childVc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
{
    // 设置子控制器的文字
    childVc.title = title;
    // 设置文字的样式
    [childVc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : kUIColorFromHex(kTextGrayColor)} forState:UIControlStateNormal];
    [childVc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : kUIColorFromHex(kNavBarColor)} forState:UIControlStateSelected];
    childVc.view.backgroundColor = [UIColor whiteColor];
    // 设置子控制器的tabBarItem图片
    childVc.tabBarItem.image = [UIImage imageNamed:image];
    // 禁用图片渲染
    childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 为子控制器包装导航控制器
    QSNavigationController *navigationVc = [[QSNavigationController alloc] initWithRootViewController:childVc];
    // 添加子控制器
    [self addChildViewController:navigationVc];
}

#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if (viewController == [tabBarController.viewControllers objectAtIndex:2] || viewController == [tabBarController.viewControllers objectAtIndex:3]) {
        verifyFlag = YES;
        
        if (viewController == [tabBarController.viewControllers objectAtIndex:2]) {
            index = 2;
        } else if (viewController == [tabBarController.viewControllers objectAtIndex:3]) {
            index = 3;
        }
        
        // 验证用户是否登录
        NSInteger resultNumber = [[QSNetworkTool shareNetworkInstance] validateCookieExpiresDateIsEffective];
        if (resultNumber != 3) {
            return NO;
        } else if (index == 2) {
            verifyFlag = NO;
            [self.tabBar hideBadgeOnItemIndex:2];
            [self jumpToCustomerServiceVC];
            return NO;
        }
    } else {
        index = -1;
    }
    return YES;
}

#pragma mark - 通知的方法实现
/**
 *  登录成功
 */
- (void)loginSuccess
{
    // 开启客服会话
    [self chatAction];
    
    if (verifyFlag) {
        if (index == 3) {
            self.selectedIndex = index;
        } else if (index == 2) {
            [self.tabBar hideBadgeOnItemIndex:2];
            HChatClient *client = [HChatClient sharedClient];
            if (client.isLoggedInBefore) {
                [self jumpToCustomerServiceVC];
            } else {
                [[QSValidateAndPromptTool shareQSValidateAndPromptTool] showAlertViewWithMessage:@"您的客服账号尚未登录，请退出程序后重新登录！"];
            }
        }
    }
    verifyFlag = NO;
}

- (void)didDisAppearCustormerServiceVC
{
    index = self.selectedIndex;
}

/**
 *  跳转到客服
 */
- (void)jumpToCustomerServiceVC
{
    QSCustomerServiceViewController *customerServiceVC = [[QSCustomerServiceViewController alloc] init];
    QSNavigationController *nav = [[QSNavigationController alloc] initWithRootViewController:customerServiceVC];
    customerServiceVC.title = @"客服";
    customerServiceVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:^{
        index = 2;
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
